package com.example.health_life.controller;

import com.example.health_life.Response;
import com.example.health_life.dao.Product;
import com.example.health_life.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public Response<List<Product>> findAll() {
        List<Product> products = productService.findAll();
        return Response.newSuccess(products);
    }

    @GetMapping("/title/{title}")
    public Response<List<Product>> getProductByTitle(@PathVariable String title) {
        List<Product> productList = productService.findByTitle(title);
        return Response.newSuccess(productList);
    }

    @GetMapping("/type/{type}")
    public Response<List<Product>> findByType(@PathVariable Byte type) {
        List<Product> products = productService.findByType(type);
        return Response.newSuccess(products);
    }

    @GetMapping("/{id}")
    public Response<Product> findById(@PathVariable Integer id) {
        Product product = productService.findById(id);
        return Response.newSuccess(product);
    }

    @PostMapping
    public Response<Integer> addProduct(@RequestBody Product product) {
        return Response.newSuccess(productService.addProduct(product));
    }

    @PutMapping("/{id}")
    public Response<Integer> updateProduct(@PathVariable Integer id, @RequestBody Product product) {
        return Response.newSuccess(productService.updateProduct(id, product));
    }

    @DeleteMapping("/{id}")
    public Response<String> deleteProduct(@PathVariable Integer id) {
        productService.deleteProduct(id);
        return Response.newSuccess("商品删除成功");
    }
}
